using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using Traceability.API.APPLications.Commands.ProductShow;
using Traceability.API.Dtos;
using Traceability.ErrorCode;
using Traceability.Infrastructure;
using Traceability.Domain;

namespace Traceability.API.APPLications.CommandHanders.ProductShow;

public class ProductListQueryHandler : IRequestHandler<ProductListQuery, APIResult<List<ProductDto>>>
{
    private readonly IBaseRepository<Products> _productRepository;
    public ProductListQueryHandler(IBaseRepository<Products> productRepository)
    {
        _productRepository = productRepository;
    }

    public Task<APIResult<List<ProductDto>>> Handle(ProductListQuery request, CancellationToken cancellationToken)
    {
        APIResult<List<ProductDto>> result = new APIResult<List<ProductDto>>();
        var products = _productRepository.GetAll()
            .Select(p => new ProductDto
            {
                ProductId = p.ProductId,
                ProductName = p.ProductName
            }).ToList();

        result.Code = APIEnum.查询成功;
        result.Message = APIEnum.查询成功.ToString();
        result.Data = products;
        return Task.FromResult(result);
    }
}